package com.itheima.tlias.controller;

import com.github.pagehelper.Page;
import com.itheima.tlias.pojo.Clazz;
import com.itheima.tlias.pojo.PageResult;
import com.itheima.tlias.pojo.Result;
import com.itheima.tlias.service.ClazzService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/clazzs")
@Slf4j
public class ClazzController {
    @Autowired
    ClazzService clazzService;


    //查询所有班级
    @GetMapping("/list")
    public Result findAll() {
        List<Clazz> clazzes = clazzService.findAll();
        return Result.success(clazzes);
    }

    //条件查询班级
    @GetMapping
    public Result queryClazz(String name,
                             @RequestParam(defaultValue = "1970-01-01")
                           @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                             @RequestParam(defaultValue = "2050-01-01")
                           @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end,
                             @RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "10") int pageSize) {
        Clazz clazz = Clazz.builder().name(name).beginDate(begin).endDate(end).build();
        List<Clazz> clazzes = clazzService.queryClazz(clazz, page, pageSize);
        Long total = ((Page)clazzes).getTotal();
        return Result.success(new PageResult(total, clazzes));
    }
    //添加班级
    @PostMapping
    public Result insert(@RequestBody Clazz clazz) {

        Integer insert = clazzService.insert(clazz);
        if (insert > 0) {
            return Result.success();
        }
        return Result.error("添加失败");
    }

    //修改班级参数回显操作
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        Clazz clazz = clazzService.findById(id);
        return Result.success(clazz);
    }
    //修改班级
    @PutMapping
    public Result update(@RequestBody Clazz clazz) {
        Integer update = clazzService.update(clazz);
        if (update > 0) {
            return Result.success();
        }
        return Result.error("修改失败");
    }
    //删除班级
        @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        Integer delete = clazzService.delete(id);
        if (delete > 0) {
            return Result.success();
        }
        return Result.error("删除失败，请检查该班级内是否还有学生！");
    }

}
